﻿using MediatR;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.FarmedCommand;
using Swork03_28.Domain.TraceableInfos;
using Swork03_28.Services.Interface;

namespace Swork03_28.Api.Application.CommandHandlers.FarmedHandler
{
    public class FirmCreateCommandHandler : IRequestHandler<FirmCreateCommand, int>
    {
        private readonly IRepository<FirmInfo> _firmInfo;
        private readonly IFarmedService farmedService;

        public FirmCreateCommandHandler(IRepository<FirmInfo> firmInfo, IFarmedService farmedService)
        {
            _firmInfo = firmInfo;
            this.farmedService = farmedService;
        }

        public async Task<int> Handle(FirmCreateCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            var info = await farmedService.GetValues(x => x.BatchId == request.BatchId);
            var res = info.FirstOrDefault();
            if (res != null)
            {
                count += await _firmInfo.UpdateAsync(new FirmInfo()
                {
                    Id = res.FarmId,
                    BatchId = request.BatchId,
                    CompanyName = request.CompanyName,
                    Principal = request.Principal,
                    Quantity = request.Quantity,
                    CampanyImage = request.CampanyImage,
                    FirmType = FirmType.养殖公司
                });
                if (res.FarmId == 0)
                {
                    var firm = await _firmInfo.GetValues(x => x.BatchId == request.BatchId);
                    var id = firm.FirstOrDefault().Id;
                    res.FarmId = id;
                    await farmedService.UpdateAsync(res);
                }
            }
            else
            {
                count += await _firmInfo.CreateAsync(new FirmInfo()
                {
                    BatchId = request.BatchId,
                    CompanyName = request.CompanyName,
                    Principal = request.Principal,
                    Quantity = request.Quantity,
                    FirmType = FirmType.养殖公司
                });
                var firm = await _firmInfo.GetValues(x => x.BatchId == request.BatchId);
                var id = firm.FirstOrDefault().Id;
                await farmedService.CreateAsync(new Farmed()
                {
                    FarmId = id,
                    BatchId = request.BatchId,
                    Brand = null,
                    Principal = null,
                    Breed = null,
                    Certificate = null,
                    Feeding = 0,
                    PublicationDate = null,
                    Source = null
                });
            }
            return count;
        }
    }
}
